﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using hotel.Win.BaseData;
using hotel.DAL;
using hotel.Common;
using hotel.Win.Common;
namespace hotel.Win.Systems
{
    /// <summary>
    /// 系统用户权限-主浏览页面
    /// </summary>
    public partial class xtyhqxFrm : Form
    {

        private hotelEntities _context;
        public xtyhqxFrm()
        {
            if (!UserLoginInfo.HaveRole(EnumRoole.Admin))
                throw new Exception("你没有" + RoleConst.Admin + "权限，不能使用本模块");
            InitializeComponent();
            _context = MyDataContext.GetDataContext;
            tabMain.SelectedIndex = 0;
            treeyhcd.Nodes.Clear();
            btnsave.Enabled = false;
            BindYHXX(true);
        }

        /// <summary>
        /// 绑定用户信息
        /// </summary>
        /// <param name="isChanged"></param>
        private void BindYHXX(bool isChanged)
        {
            if (!isChanged)
                return;
            gridyh.AutoGenerateColumns = false;
            gridyh.DataSource = null;
            gridyh.DataSource = _context.XTYH.AsNoTracking().OrderBy(p => p.XM).ToList();
        }

        private void btnclose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnsave_Click(object sender, EventArgs e)
        {
            if (tabMain.SelectedIndex == 0)
            {
                SaveCDQX();
            }
            else if (tabMain.SelectedIndex == 1)
            {
                SaveYHJS();
            }

            #region 日志纪录
            var logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.增加数据;
            logInfo.Type = LogTypeEnum.一般操作;
            logInfo.Message = "修改用户权限配置" ;
            logInfo.Save();
            #endregion
        }

        private void SaveYHJS()
        {
            string id = Common.ControlsUtility.GetActiveGridValue(gridyh, "ID");
            if (id == "")
                return;
            foreach (var item in _context.YHJS.Where(p => p.YHID == id))
            {
                _context.YHJS.Remove(item);
            }
            foreach (NameValue item in chklstYhjs.CheckedItems)
            {
                var yhjsModel = new YHJS { YHID = id, JSID = item.Value };
                XTJS xtjs = _context.XTJS.Where(p => p.ID == item.Value).FirstOrDefault();
                xtjs.YHJS.Add(yhjsModel);
                XTYH xtyh = _context.XTYH.Where(p => p.ID == id).FirstOrDefault();
                xtyh.YHJS.Add(yhjsModel);
                _context.YHJS.Add(yhjsModel);
            }
            _context.SaveChanges();
            MessageBox.Show("用户角色配置保存成功");
        }

        private void PrintRecursive(TreeNode treeNode)
        {
            //效率有点差，要一条条更新，如果太慢考虑优化
            int id = Convert.ToInt32(treeNode.Tag);
            var model = _context.CDQX.First(p => p.ID == id);
            model.SFKY = treeNode.Checked ? 1 : 0;
            // each node recursively.
            foreach (TreeNode tn in treeNode.Nodes)
            {
                PrintRecursive(tn);
            }
        }

        private void SaveCDQX()
        {
            TreeNodeCollection nodes = treeyhcd.Nodes;
            foreach (TreeNode n in nodes)
            {
                PrintRecursive(n);
            }
            _context.SaveChanges();
            MessageBox.Show("用户菜单权限配置保存成功");
        }


        private void btnyhbj_Click(object sender, EventArgs e)
        {
            yhMaintain frm;
            string id = Common.ControlsUtility.GetActiveGridValue(gridyh, "ID");
            if (id == "")
                frm = new yhMaintain(true);
            else
                frm = new yhMaintain(id);
            frm.CallBack = BindYHXX;
            frm.ShowDialog();
        }


        private List<NameValue> GetALLXTJS()
        {
            return (from q in _context.XTJS
                    orderby q.JSMC
                    select new NameValue { Name = q.JSMC, Value = q.ID }).ToList();
        }
        private void gridyh_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string yhid = Common.ControlsUtility.GetActiveGridValue(gridyh, "ID");
            btnsave.Enabled = true;
            //绑定用户菜单
            BindCDQX(yhid);
            //绑定用户角色
            BindYHJS(yhid);

        }
        //private TreeNode FindTreeNode(string key)
        //{
        //    var nodes = treeyhcd.Nodes.Find(key,true);
        //    if (nodes != null && nodes.Count() > 0)
        //        return nodes.First();
        //    else
        //        return null;
        //}

        private void BindCDQX(string yhid)
        {
            var cds = from q in _context.CDQX
                      where q.XTYH.ID == yhid
                      orderby q.F_CDBM, q.ZXH
                      select q;
            if (cds.Count() == 0)
            {
                if (MessageBox.Show("用户菜单还不存在，是否初始化？", SysConsts.SysInformationCaption, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    _context.PROC_InitUserMenu(yhid);
                else
                    return;
                cds = from q in _context.CDQX
                      where q.XTYH.ID == yhid
                      orderby q.F_CDBM, q.ZXH
                      select q;
            }
            treeyhcd.SuspendLayout();
            treeyhcd.Nodes.Clear();
            var dic = new Dictionary<string, TreeNode>();
            TreeNode node;
            foreach (var item in cds)
            {
                node = new TreeNode();
                node.Text = item.CDMC;
                node.Checked = item.SFKY == 1;
                node.Name = item.Z_CDBM;
                node.Tag = item.ID;
                if (string.IsNullOrEmpty(item.F_CDBM))
                {
                    dic.Add(item.Z_CDBM, node);
                    treeyhcd.Nodes.Add(node);
                }
                else
                {
                    dic[item.F_CDBM].Nodes.Add(node);
                }
            }
            treeyhcd.ExpandAll();
            treeyhcd.ResumeLayout();
        }

        private void BindYHJS(string yhid)
        {

            chklstYhjs.Items.Clear();
            foreach (var item in GetALLXTJS())
            {
                chklstYhjs.Items.Add(item);
            }

            var yhjs = _context.YHJS.Where(p => p.YHID == yhid);
            if (yhjs.Count() > 0)
            {
                for (int i = 0; i < chklstYhjs.Items.Count; i++)
                {
                    string jsid = (chklstYhjs.Items[i] as NameValue).Value;
                    if (yhjs.Where(p => p.JSID == jsid).Count() == 1)
                        chklstYhjs.SetItemChecked(i, true);
                }
            }
        }

        private void treeyhcd_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action == TreeViewAction.ByMouse)
            {
                if (e.Node.Checked)
                {
                    setChildNodeCheckedState(e.Node, true);
                    if (e.Node.Parent != null)
                    {
                        setParentNodeCheckedState(e.Node, true);
                    }
                }
                else
                {
                    setChildNodeCheckedState(e.Node, false);
                    //如果节点存在父节点，取消父节点的选中状态
                    //if (e.Node.Parent != null)
                    //{
                    //    setParentNodeCheckedState(e.Node, false);
                    //}
                }
            }
        }
        //取消节点选中状态之后，取消所有父节点的选中状态

        private void setParentNodeCheckedState(TreeNode currNode, bool state)
        {
            TreeNode parentNode = currNode.Parent;
            parentNode.Checked = state;
            if (currNode.Parent.Parent != null)
            {
                setParentNodeCheckedState(currNode.Parent, state);
            }

        }
        //选中节点之后，选中节点的所有子节点

        private void setChildNodeCheckedState(TreeNode currNode, bool state)
        {
            TreeNodeCollection nodes = currNode.Nodes;
            if (nodes.Count > 0)
            {
                foreach (TreeNode tn in nodes)
                {
                    tn.Checked = state;
                    setChildNodeCheckedState(tn, state);
                }
            }
        }

        private void tmi_deletey_Click(object sender, EventArgs e)
        {
            string yhid = Common.ControlsUtility.GetActiveGridValue(gridyh, "ID");
            if (yhid == "")
                return;
            if (yhid == SysConsts.SystemAdminId)
            {
                MessageBox.Show("此用户为系统管理员，不能删除");
                return;
            }
            if (MessageBox.Show("你确定要强制删除此用户？", SysConsts.SysInformationCaption, MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;

            _context.PROC_XTYH_Delete(yhid);
            MessageBox.Show("用户已经删除成功！");
            BindYHXX(true);
            treeyhcd.Nodes.Clear();
            btnsave.Enabled = false;
        }
    }
}
